package com.cn.medicalcare.controller.frontservlet;

import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.pojo.Page;
import com.cn.medicalcare.pojo.Product;
import com.cn.medicalcare.service.ProductService;
import com.cn.medicalcare.service.serviceimpl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/getproductbycateid.json")
public class ProducteByCateIdServlet extends HttpServlet {

    public static final int PAGELIMIT = 8;

    protected ProductService productService = ProductServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, Object> map = new LinkedHashMap<>();
        try {
            int cate_id = Integer.parseInt(req.getParameter("cate_id"));
            int pagenum = Integer.parseInt(req.getParameter("pagenum"));
            Page page = null;
            if (pagenum > 0)
                page = new Page((pagenum - 1) * PAGELIMIT, PAGELIMIT);
            List<Product> list = productService.selectProductByCateId(cate_id, page);
            if (list != null && list.size() > 0) {
                map.put("status", 200);
                map.put("data", list);
            } else {
                map.put("status", 404);
            }
        } catch (Exception e) {
            map.put("status", 500);
        }
        resp.getWriter().print(JsonTool.toJson(map));
    }

}
